package com.baoxin.chenxixc4coach;

import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AlertDialog;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;

import com.baoxin.chenxixc4coach.bean.AdvanceCourse;
import com.baoxin.chenxixc4coach.java.MyHandler;
import com.baoxin.chenxixc4coach.utils.DensityUtil;
import com.baoxin.chenxixc4coach.utils.Interfaces;
import com.baoxin.chenxixc4coach.utils.ListSaveUtils;
import com.baoxin.chenxixc4coach.utils.Msg;
import com.baoxin.chenxixc4coach.utils.NetUtil;
import com.baoxin.chenxixc4coach.utils.TimeUtil;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

public class CourseSettingActivity extends BaseActivity {

    static final String ADVANCE_MOULD_NAME = "advance_moduld";
    String[] items = new String[]{"科目二", "科目三"};
    private int subject_tag = 2;

    private TextView mStartDay;
    private TextView mEndDay;
    private LinearLayout courseLL;
    private Button bottomView;
    private String startYMD;
    private String endYMD;
    private Calendar currentCalendar;
    private Calendar startCalendar;
    private Calendar endCalendar;
    private List<AdvanceCourse> advanceCourseList;

    private EditText mRule1;
    private EditText mRule2;
    private EditText mRule3;
    private EditText mRule4;
    private EditText mRule5;

    private Handler handler;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_course_setting);

        mStartDay = findViewById(R.id.start_day);
        mEndDay = findViewById(R.id.end_day);
        courseLL = findViewById(R.id.course_ll);
        mRule1 = findViewById(R.id.rule1);
        mRule2 = findViewById(R.id.rule2);
        mRule3 = findViewById(R.id.rule3);
        mRule4 = findViewById(R.id.rule4);
        mRule5 = findViewById(R.id.rule5);

        currentCalendar = Calendar.getInstance();
        startCalendar = Calendar.getInstance();
        endCalendar = Calendar.getInstance();

        int year = currentCalendar.get(Calendar.YEAR);
        int month = currentCalendar.get(Calendar.MONTH);
        int dayOfMonth = currentCalendar.get(Calendar.DAY_OF_MONTH);
        month += 1;
        startYMD = year + "/" + month + "/" + dayOfMonth;
        endYMD = startYMD;
        mStartDay.setText(startYMD);
        mEndDay.setText(endYMD);

        startCalendar.setTime(TimeUtil.StrToDate(startYMD, "yyyy/MM/dd"));
        endCalendar.setTime(TimeUtil.StrToDate(endYMD, "yyyy/MM/dd"));

        LinearLayout rootView = findViewById(R.id.root_view);
        bottomView = findViewById(R.id.release);

        rootView.addOnLayoutChangeListener(new View.OnLayoutChangeListener() {
            @Override
            public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) {
                if (oldBottom - bottom > 1) {//布局发生变化，底部上去了（软键盘弹出）//软键盘弹上去了,动态设置高度为0
                    LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 0);
                    bottomView.setLayoutParams(params);
                } else if (oldBottom - bottom < -1) {//软键盘弹下去
                    LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                            DensityUtil.dp2px(CourseSettingActivity.this, 48f));
                    bottomView.setLayoutParams(params);
                }
            }
        });
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);

        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayShowTitleEnabled(false);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        handler = new MyHandler(this, activity) {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                switch (msg.what) {
                    case Msg.REQUEST_SUCCEED:
                        Dialog dialog = new Dialog(activity);
                        View contentView = LayoutInflater.from(activity).inflate(R.layout.release_success_dialog, null);
                        TextView title = contentView.findViewById(R.id.title);
                        title.setText(msg.getData().getString("msg"));
                        //否则背景radius会失效
                        dialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent);
                        dialog.setContentView(contentView);
                        dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
                            @Override
                            public void onDismiss(DialogInterface dialog) {
                                setResult(1);
                                finish();
                            }
                        });
                        dialog.show();
                        break;
                }


            }
        };

    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    /**
     * 选择科目
     *
     * @param view
     */
    public void onSelectSubject(final View view) {

        AlertDialog dialog = new AlertDialog.Builder(this).setTitle("选择科目")
                .setItems(items, new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        ((TextView) view).setText(items[which]);
                        subject_tag = which + 2;
                        dialog.dismiss();
                    }
                }).create();
        dialog.show();
    }


    /**
     * 起始日
     *
     * @param view
     */
    public void onStartDay(View view) {
        DatePickerDialog datePickerDialog = new DatePickerDialog(this,
                new DatePickerDialog.OnDateSetListener() {
                    @Override
                    public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
                        month += 1;
                        startYMD = year + "/" + month + "/" + dayOfMonth;
                        startCalendar.setTime(TimeUtil.StrToDate(startYMD, "yyyy/MM/dd"));
                        mStartDay.setText(startYMD);
                        //更新endDay
                        resetEndDate();
                    }
                },
                currentCalendar.get(Calendar.YEAR),
                currentCalendar.get(Calendar.MONTH),
                currentCalendar.get(Calendar.DAY_OF_MONTH));
        datePickerDialog.getDatePicker().setMinDate(currentCalendar.getTimeInMillis());
        datePickerDialog.show();
    }

    /**
     * 终止日
     *
     * @param view
     */
    public void onEndDay(View view) {
        DatePickerDialog datePickerDialog = new DatePickerDialog(this,
                new DatePickerDialog.OnDateSetListener() {
                    @Override
                    public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
                        month += 1;
                        endYMD = year + "/" + month + "/" + dayOfMonth;
                        endCalendar.setTime(TimeUtil.StrToDate(endYMD, "yyyy/MM/dd"));
                        mEndDay.setText(endYMD);
                    }
                },
                startCalendar.get(Calendar.YEAR),
                startCalendar.get(Calendar.MONTH),
                startCalendar.get(Calendar.DAY_OF_MONTH));
        datePickerDialog.getDatePicker().setMinDate(startCalendar.getTimeInMillis());
        datePickerDialog.show();
    }

    /**
     * 设置初始日期后结束，结束日期相应进行合理变化
     */
    private void resetEndDate() {
        if (startCalendar.getTimeInMillis() > endCalendar.getTimeInMillis()) {
            endCalendar.setTime(startCalendar.getTime());
            mEndDay.setText(startYMD);
            endYMD = startYMD;
        }
    }


    public void onAddCourse(View view) {
        LinearLayout.LayoutParams params1 = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT);
        params1.topMargin = 45;//px
        LinearLayout courseView = createCourseView();

        courseLL.addView(courseView, params1);
    }


    /**
     * 创建课程view
     *
     * @return
     */
    private LinearLayout createCourseView() {
        final LinearLayout courseView = (LinearLayout) LayoutInflater.from(this).inflate(R.layout.single_course, null);

        TextView mStartTime = courseView.findViewById(R.id.start_time);
        TextView mEndTime = courseView.findViewById(R.id.end_time);
        EditText mNumber = courseView.findViewById(R.id.number);
        EditText mPrice = courseView.findViewById(R.id.price);
        ImageView mDelete = courseView.findViewById(R.id.delete);

        if (indexOfSave < sizeOfSave) {
            AdvanceCourse advanceCourse = advanceCourseList.get(indexOfSave);
            mStartTime.setText(advanceCourse.startStr);
            mEndTime.setText(advanceCourse.endStr);
            mNumber.setText("" + advanceCourse.number);
            mPrice.setText("" + advanceCourse.price);
            indexOfSave++;
        }
        mStartTime.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(final View v) {
                TimePickerDialog timePickerDialog = new TimePickerDialog(CourseSettingActivity.this,
                        new TimePickerDialog.OnTimeSetListener() {
                            @Override
                            public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
                                StringBuilder sb = new StringBuilder();
                                if (hourOfDay > 9) {
                                    sb.append(hourOfDay);
                                } else {
                                    sb.append("0").append(hourOfDay);
                                }
                                sb.append(":");
                                if (minute > 9) {
                                    sb.append(minute);
                                } else {
                                    sb.append("0").append(minute);
                                }
                                ((TextView) v).setText(sb);
                            }
                        }, 8, 0, true);
                timePickerDialog.show();
            }
        });

        mEndTime.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(final View v) {
                TimePickerDialog timePickerDialog = new TimePickerDialog(CourseSettingActivity.this,
                        new TimePickerDialog.OnTimeSetListener() {
                            @Override
                            public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
                                StringBuilder sb = new StringBuilder();
                                if (hourOfDay > 9) {
                                    sb.append(hourOfDay);
                                } else {
                                    sb.append("0").append(hourOfDay);
                                }
                                sb.append(":");
                                if (minute > 9) {
                                    sb.append(minute);
                                } else {
                                    sb.append("0").append(minute);
                                }
                                ((TextView) v).setText(sb);
                            }
                        }, 8, 0, true);
                timePickerDialog.show();
            }
        });

        mDelete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                courseLL.removeView(courseView);
            }
        });
        return courseView;
    }


    /**
     * 发布课程
     *
     * @param view
     */
    public void onRelease(View view) {

        saveOrRelease(1);

    }

    /**
     * 保存课程
     *
     * @param view
     */
    public void onSave(View view) {

        saveOrRelease(0);

    }

    /**
     * @param tag 0=保存  1=发布
     */
    private void saveOrRelease(int tag) {
        if (!pass()) {
            return;
        }

        JSONArray courses = new JSONArray();

        for (int i = 0; i < advanceCourseList.size(); i++) {

            AdvanceCourse advanceCourse = advanceCourseList.get(i);

            JSONObject course = new JSONObject();
            try {
                course.put("ofadStartTime", advanceCourse.start.getTime());
                course.put("ofadEndTime", advanceCourse.end.getTime());
                course.put("ofadMaxNum", advanceCourse.number);
                course.put("ofadPrice", advanceCourse.price);
                course.put("ofadAtime", advanceCourse.price);
                course.put("ofadBtime", advanceCourse.price);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            courses.put(course);

        }

        JSONObject result = new JSONObject();
        try {
            result.put("ofaState", tag);//0待发布，1发布
            result.put("subject", subject_tag);
            result.put("startDate", startYMD);
            result.put("endDate", endYMD);
            ;

            result.put("ofadEarlyTime", Integer.parseInt(mRule1.getText().toString()) * 60 * 60 * 1000);
            result.put("ofadLateTime", Integer.parseInt(mRule2.getText().toString()) * 60 * 60 * 1000);
            result.put("temp", courses.toString());//for rio,实际应该是 result.put("temp", courses.toString());
        } catch (JSONException e) {
            e.printStackTrace();
        }

        try {
            NetUtil.post(this, Interfaces.URL_RELEASE_COURSES, result.toString(), new MyCallback(Interfaces.URL_RELEASE_COURSES, handler));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 不合理不通过
     *
     * @return
     */
    private boolean pass() {
        int courseSize = courseLL.getChildCount();
        if (courseSize == 0) {
            Toast.makeText(this, "未设置课程！", Toast.LENGTH_SHORT).show();
            return false;
        }
        if (isIllegal()) {
            Toast.makeText(this, "课程设置有误！", Toast.LENGTH_SHORT).show();
            return false;
        }
        return true;
    }

    /**
     * advanceCourseList先储存课程,再检测课程时间是否合理
     */
    private boolean isIllegal() {

        int courseSize = courseLL.getChildCount();
        advanceCourseList = new ArrayList<>();
        for (int i = 0; i < courseSize; i++) {
            LinearLayout linearLayout = (LinearLayout) courseLL.getChildAt(i);
            TextView startTime = linearLayout.findViewById(R.id.start_time);
            TextView endTime = linearLayout.findViewById(R.id.end_time);
            EditText mNumber = linearLayout.findViewById(R.id.number);
            EditText mPrice = linearLayout.findViewById(R.id.price);

            Date startDate = TimeUtil.StrToDate(startYMD + " " + startTime.getText().toString(), "yyyy/MM/dd HH:mm");
            Date endDate = TimeUtil.StrToDate(endYMD + " " + endTime.getText().toString(), "yyyy/MM/dd HH:mm");

            AdvanceCourse h = new AdvanceCourse(startDate, endDate);
            h.startStr = startTime.getText().toString();
            h.endStr = endTime.getText().toString();
            h.number = Integer.parseInt(mNumber.getText().toString());
            h.price = Integer.parseInt(mPrice.getText().toString());

            advanceCourseList.add(h);
        }

        for (int i = 0; i < courseSize; i++) {
            AdvanceCourse h = advanceCourseList.get(i);
            if (h.start.getTime() >= h.end.getTime()) {
                return true;
            }
            for (int j = 0 + 1 + i; j < courseSize; j++) {
                AdvanceCourse h2 = advanceCourseList.get(j);
                if (isConflict(h.start, h.end, h2.start, h2.end)) {
                    return true;
                }
            }
        }
        return false;

    }

    /**
     * 判断2个课程之间是否有冲突
     *
     * @param start
     * @param end
     * @param start1
     * @param end1
     * @return
     */
    private boolean isConflict(Date start, Date end, Date start1, Date end1) {

        if (start.getTime() > start1.getTime() && start.getTime() < end1.getTime()) {
            return true;
        } else if (end.getTime() > start1.getTime() && end.getTime() < end1.getTime()) {
            return true;
        } else if (start.getTime() == start1.getTime() && end.getTime() == end1.getTime()) {
            return true;
        } else if (start1.getTime() > start.getTime() && start1.getTime() < end.getTime()) {
            return true;
        } else if (end1.getTime() > start.getTime() && end1.getTime() < end.getTime()) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 获取设置课程天数
     *
     * @return
     */
    private int getDays() {

        final long MILLIS_OF_DAY = 24 * 60 * 60 * 1000;

        long startMillis = startCalendar.getTimeInMillis();
        long endMillis = endCalendar.getTimeInMillis();

        int startDays = (int) (startMillis / MILLIS_OF_DAY);
        int endDays = (int) (endMillis / MILLIS_OF_DAY);

        return endDays - startDays + 1;

    }

    /**
     * Go-->时间模板
     *
     * @param view
     */
    public void onMould(View view) {
        Intent intent = new Intent(this, AdvanceMouldActivity.class);
        startActivityForResult(intent, 1);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == 1 && resultCode == 1) {
            courseLL.removeAllViews();
            initCourseViewBySave();
        }

    }

    //存在本地的数据数量
    int sizeOfSave;
    int indexOfSave = 0;

    private void initCourseViewBySave() {
        advanceCourseList = ListSaveUtils.getDataEntities(ADVANCE_MOULD_NAME);
        sizeOfSave = advanceCourseList.size();
        indexOfSave = 0;
        for (int i = 0; i < sizeOfSave; i++) {
            onAddCourse(null);
        }
    }
}